#!/bin/bash

# 环境工程咨询系统一键部署脚本（国内镜像版）
# 服务器: 121.37.182.125
# 项目: https://gitee.com/lizaoboss/gzqhsz.git

set -e

echo "🚀 开始一键部署环境工程咨询系统（国内镜像加速版）..."

# 检测系统版本
UBUNTU_VERSION=$(lsb_release -rs 2>/dev/null || echo "22.04")
UBUNTU_CODENAME=$(lsb_release -cs 2>/dev/null || echo "jammy")

echo "📋 检测到系统版本: Ubuntu $UBUNTU_VERSION ($UBUNTU_CODENAME)"

# 配置国内镜像源
echo "🔧 配置Ubuntu国内镜像源..."

# 备份原始sources.list
cp /etc/apt/sources.list /etc/apt/sources.list.backup.$(date +%Y%m%d_%H%M%S)

# 根据系统版本配置对应的镜像源
if [[ "$UBUNTU_CODENAME" == "jammy" ]]; then
    # Ubuntu 22.04
    cat > /etc/apt/sources.list << 'EOF'
# 阿里云镜像源 - Ubuntu 22.04 LTS
deb http://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
EOF
elif [[ "$UBUNTU_CODENAME" == "noble" ]]; then
    # Ubuntu 24.04
    cat > /etc/apt/sources.list << 'EOF'
# 阿里云镜像源 - Ubuntu 24.04 LTS
deb http://mirrors.aliyun.com/ubuntu/ noble main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ noble main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ noble-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ noble-security main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ noble-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ noble-updates main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ noble-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ noble-backports main restricted universe multiverse
EOF
else
    # 其他版本使用通用配置
    sed -i 's|http://archive.ubuntu.com/ubuntu/|http://mirrors.aliyun.com/ubuntu/|g' /etc/apt/sources.list
    sed -i 's|http://security.ubuntu.com/ubuntu/|http://mirrors.aliyun.com/ubuntu/|g' /etc/apt/sources.list
fi

# 更新系统
echo "📦 更新系统..."
apt update && apt upgrade -y

# 安装必要软件
echo "🔧 安装必要软件..."
apt install -y python3 python3-pip python3-venv nodejs npm nginx git curl ufw lsb-release

# 配置pip国内镜像源
echo "🔧 配置pip国内镜像源..."
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << 'EOF'
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
timeout = 120

[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
EOF

# 配置npm国内镜像源
echo "🔧 配置npm国内镜像源..."
npm config set registry https://registry.npmmirror.com
npm config set cache ~/.npm
npm config set electron_mirror https://npmmirror.com/mirrors/electron/
npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
npm config set phantomjs_cdnurl https://npmmirror.com/mirrors/phantomjs/
npm config set python_mirror https://npmmirror.com/mirrors/python/

# 安装PM2
echo "📋 安装PM2..."
npm install -g pm2

# 克隆项目
echo "📥 克隆项目..."
cd /var/www
if [ -d "environmental-consulting" ]; then
    echo "🗑️ 删除旧项目..."
    rm -rf environmental-consulting
fi

# 使用Gitee镜像
git clone https://gitee.com/lizaoboss/gzqhsz.git environmental-consulting
cd environmental-consulting

# 配置git使用国内镜像（如果需要后续更新）
git config --global url."https://gitee.com/".insteadOf "https://github.com/"

# 运行项目部署脚本
echo "🏗️ 运行项目部署..."
chmod +x deploy.sh

# 临时设置环境变量使用国内镜像
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
export PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn

./deploy.sh production

# 配置环境变量
echo "⚙️ 配置环境变量..."
cd backend
cat > .env << 'EOF'
# 数据库配置
DATABASE_URL=sqlite:///./environmental_consulting.db

# JWT密钥
SECRET_KEY=gzqhsz-environmental-consulting-super-secret-key-2024

# 应用配置
DEBUG=false
HOST=0.0.0.0
PORT=8001

# 前端URL
FRONTEND_URL=https://gzqhst.com
EOF

cd ..

# 配置Nginx
echo "🌐 配置Nginx..."
sed -i 's/your-domain.com/gzqhst.com/g' nginx.conf
sed -i 's|/path/to/your/project|/var/www/environmental-consulting|g' nginx.conf

cp nginx.conf /etc/nginx/sites-available/environmental-consulting
ln -sf /etc/nginx/sites-available/environmental-consulting /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl restart nginx
systemctl enable nginx

# 配置PM2
echo "🔄 配置PM2..."
sed -i 's|/path/to/your/project|/var/www/environmental-consulting|g' ecosystem.config.js
mkdir -p logs

pm2 start ecosystem.config.js
pm2 save
pm2 startup --hp /root

# 配置防火墙
echo "🔒 配置防火墙..."
ufw allow 22
ufw allow 80
ufw allow 443
ufw --force enable

# 创建系统服务监控脚本
echo "📊 创建监控脚本..."
cat > /usr/local/bin/check-environmental-consulting.sh << 'EOF'
#!/bin/bash
# 检查服务状态并自动重启

# 检查PM2服务
if ! pm2 list | grep -q "environmental-api.*online"; then
    echo "$(date): PM2服务异常，正在重启..." >> /var/log/environmental-consulting.log
    cd /var/www/environmental-consulting
    pm2 restart environmental-api
fi

# 检查Nginx服务
if ! systemctl is-active --quiet nginx; then
    echo "$(date): Nginx服务异常，正在重启..." >> /var/log/environmental-consulting.log
    systemctl restart nginx
fi

# 检查磁盘空间
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 90 ]; then
    echo "$(date): 磁盘空间不足，使用率: ${DISK_USAGE}%" >> /var/log/environmental-consulting.log
fi
EOF

chmod +x /usr/local/bin/check-environmental-consulting.sh

# 添加定时任务
echo "⏰ 配置定时监控..."
(crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/check-environmental-consulting.sh") | crontab -

echo "✅ 部署完成！"
echo ""
echo "🌐 访问地址:"
echo "   - 网站首页: https://gzqhst.com"
echo "   - API文档: https://gzqhst.com/docs"
echo ""
echo "🔑 默认管理员账户:"
echo "   - 用户名: admin"
echo "   - 密码: admin123"
echo ""
echo "🔧 管理命令:"
echo "   - 查看服务: pm2 status"
echo "   - 重启服务: pm2 restart environmental-api"
echo "   - 查看日志: pm2 logs environmental-api"
echo "   - 查看系统日志: tail -f /var/log/environmental-consulting.log"
echo ""
echo "📊 镜像源配置:"
echo "   - Ubuntu APT: 阿里云镜像"
echo "   - Python pip: 清华大学镜像"
echo "   - Node.js npm: npmmirror镜像"
echo ""
echo "🎉 祝您使用愉快！"
